'''
Created on 2010-10-25
This is use to modify the OpenTTD.cfg. To vary the parameters the testing required
The filepath of openttd 
Win XP : "C:\Documents and Settings\<username>\My Documents\OpenTTD"
Vista/7: "C:\Users\<username>\Documents\OpenTTD"
Linux  : "~/.openttd"
Mac OS X  : "~/Documents/OpenTTD"
@author: Q
'''
import os,ConfigParser, sys, string, time, DescriptionParser, ConfigBase
from Util import *;
import shutil

commands = ["Rondje", "Convoy", "PathZilla", "OtviAI", "choochoo", "\"Denver & Rio Grande\"", 
            "AdmiralAI", "PAXLink", "Rondje", "Convoy", "PathZilla", "OtviAI", "choochoo", "\"Denver & Rio Grande\"", 
            "AdmiralAI", "PAXLink", "Rondje", "Convoy", "PathZilla", "OtviAI", "choochoo", "\"Denver & Rio Grande\"", 
            "AdmiralAI", "PAXLink", "Rondje", "Convoy", "PathZilla", "OtviAI", "choochoo", "\"Denver & Rio Grande\"", 
            "AdmiralAI", "PAXLink"]
moreAICommands = ["Rondje", "Convoy", "PathZilla", "OtviAI", "choochoo", "\"Denver & Rio Grande\"", 
            "AdmiralAI", "PAXLink", "chopper", "streettraffic", "rocketAi", "wrightAI", "simpleAI", "mogulAI",
            "trains", "trans" ,"towncars"]

class Configuration:
    
    def getBinaryDirectoryPath(self):
        return ConfigBase.getBinaryDirectoryPath()
    
    def getFilename(self):
#        path = self.getBinaryDirectoryPath()
#        return path + "openttd.cfg"
        return ConfigBase.getFileName()
    
    def mkExpDir(self,expName):
        path = os.path.join("..", "test_result")
        if os.path.exists(path) == False:
            os.mkdir(path)
        path = os.path.join(path, expName)
        if os.path.exists(path) == False:
            os.mkdir(path)
            
    def set(self, option1, option2, val):
        config = ConfigParser.ConfigParser()
        config.optionxform=str
        filename = self.getFilename()
#        print "openttd configuration path";
#        print filename
        config.read(filename)
        ttdVersion = config.set(option1, option2, val)
        config.write(open(filename, "w"))  #At first I use the 'r+', it waste me quite a lot of time to find this stupid bug
        
    """
    Each game can run 15 years, this is done by checking the autosave, 
    and check whether it has 15 autosaves.
    """
    def removeAutoSave(self):
        autoSavePath = ConfigBase.getAutoSavePath();
        self.delete_file_folder(autoSavePath)
 
        autoSavePath = os.path.join(rt(ConfigBase.getBinaryDirectoryPath()), "save", "autosave")
        autoSavePath = fm(autoSavePath);
        self.delete_file_folder(autoSavePath)
    
    def delete_file_folder(self,src):
    #    print '''delete files and folders''' + src
        if os.path.isfile(src):
            try:
                os.remove(src)
            except:
                pass
        elif os.path.isdir(src):
            for item in os.listdir(src):
                itemsrc=os.path.join(src,item)
                self.delete_file_folder(itemsrc) 
            try:
                os.rmdir(src)
            except:
                pass
    
    def increaseId(self):
        try:
            filename = os.path.join("id")
            file = open(filename)
            line = file.readline()
            id = string.atoi(line)
            file.close()
            file = open(filename, "w")
            id = id + 1
            print >> file,id 
            file.close()
            return id
        except:
            return 0
    
    def getId(self):
        try:
            filename = os.path.join("id")
            file = open(filename)
            line = file.readline()
            id = string.atoi(line)
            return id
        except:
            return 0
    
    def getGameStartScrPath(self):
        return ConfigBase.getGameStartScrPath()
    
    def setSingleAI(self,num):
#        self.set("difficulty", "max_no_competitors", 1)
        game_start_scr_path = self.getGameStartScrPath()
#        if sys.platform == "win32":
#        #    game_start_scr_path = "c:\\program files\\openttd\\scripts\\game_start.scr"
#            game_start_scr_path = "c:\\cygwin\\home\\Q\\OpenTTD\\scripts\\game_start.scr"
#        elif sys.platform.find("linux") >=0 :
#    #        game_start_scr_path = "/home/sq/software/openttd-1.0.4/bin/scripts/game_start.scr"
#    #        game_start_scr_path = "/usr/share/games/openttd/scripts/game_start.scr"
#    #        game_start_scr_path = "/home/sshen/openttd/1.0.5/bin/scripts/game_start.scr"
#            game_start_scr_path = "../game_start.scr"
        file = open(game_start_scr_path, "w")
        print >> file, "start_ai " + moreAICommands[num-1]
        file.close()
    
    def setAI(self,num):
        game_start_scr_path = self.getGameStartScrPath()
#        if sys.platform == "win32":
#        #    game_start_scr_path = "c:\\program files\\openttd\\scripts\\game_start.scr"
#            game_start_scr_path = "c:\\cygwin\\home\\Q\\OpenTTD\\scripts\\game_start.scr"
#        elif sys.platform.find("linux") >=0 :
#    #        game_start_scr_path = "/home/sq/software/openttd-1.0.4/bin/scripts/game_start.scr"
#    #        game_start_scr_path = "/usr/share/games/openttd/scripts/game_start.scr"
#    #        game_start_scr_path = "/home/sshen/openttd/1.0.5/bin/scripts/game_start.scr"
#            game_start_scr_path = "../game_start.scr"
        file = open(game_start_scr_path, "w")
        if num == 0:
            print >>file, ""
        for i in xrange(0, num/1):
            print >> file, "start_ai " + commands[i]  
        file.close()
            
    def getMaxYear(self, expName):
        expName = ConfigBase.getNameWithReplayPrefix(expName)
        if expName.find("y")>=0:
            p1 = expName.find("y")
            for i in range(p1, 0, -1):
                if expName[i] == "-":
                    year = string.atoi(expName[i+1:p1])
                    print "Configuration get year", year
                    return year
        if expName == "1a4" or expName == "1a10" :
            return 10
        elif expName == "1a13-6":
            return 6
        elif expName.find("1a7-5")>=0 or expName == "1a13-5" or expName.find("1a11")>=0:
            return 5
        else :
            return 1
    def getAutoSaveYear(self, expName):
        return self.getMaxYear(expName) - 1
    def setRandomAI(self,num):
#        self.set("difficulty", "max_no_competitors", num)
        game_start_scr_path = self.getGameStartScrPath()
        file = open(game_start_scr_path, "w")
        for i in xrange(0, num/1):
            print >> file, "start_ai "
        file.close()
        
    def initExp(self, expName):
    #    if sys.platform.find("linux") >=0:
    #        import psyco
        """
             map size: 512x512
        - game start: 1998
        - all AI engines start at 01-01-1998
        - game length: 10
        - maximum loan: 100.000 pound
        - interest rate: 4%
        - maintenance cost: high
        - construction cost: high
        - subsidy multiplier: 2
        - economy: stable
        - inflation: none
        - disasters: off
        - city counsil: permissive
        """
#        os.system("cp ./orignopenttd.cfg ../openttd.cfg")
#        time.sleep(10)
#        cmd = "cp ./orignopenttd.cfg " + self.getFilename();
#        print cmd;
#        os.system(cmd)
        shutil.copyfile("./orignopenttd.cfg", self.getFilename());
        print "The configuration is located at", self.getFilename(), "it will be changed and copy to binary files' location"
        self.removeAutoSave() #It need to remove all the autosave
        self.set("game_creation", "starting_year", 1998)
        self.set("game_creation", "map_x", 9)
        self.set("game_creation", "map_y", 9)
        self.set("game_creation", "generation_seed", 0)
        self.set("difficulty", "number_towns", 2)
        self.set("difficulty", "number_industries", 2)
        self.set("difficulty", "max_no_competitors", 0)  
        #We need to set it to be 0, start_ai can ignore this limitation, otherwise, 
        #the game engine may start another AI
        
        self.set("difficulty", "max_loan", 300000)
        self.set("difficulty", "initial_interest", 4)
        self.set("difficulty", "vehicle_costs", 2)
        self.set("difficulty", "construction_cost", 2)
        self.set("difficulty", "subsidy_multiplier", 2)
        self.set("difficulty", "economy", 0)
        self.set("difficulty", "terrain_type", 1)
        self.set("difficulty", "quantity_sea_lakes", 2)
        self.set("economy", "inflation", "false")
        self.set("difficulty", "disasters", 0)
        self.set("difficulty", "town_council_tolerance", 0)
        
        self.set("vehicle", "max_roadveh", 500)
        self.set("vehicle", "max_trains", 500)
        self.set("vehicle", "max_aircraft", 200)
        self.set("vehicle", "max_ships", 300)
        
        self.set("economy", "initial_city_size", 2)
        self.set("economy", "town_growth_rate", 2)
        self.set("economy", "larger_towns", 4)
        self.set("gui", "autosave", "monthly")
#        self.set("gui", "autosave", "yearly")
        
        self.set("ai", "ai_max_opcode_till_suspend", 10000)
        self.setAI(0)
        return True
    
    def __init__(self):
        self.path = "1"
        self.hostname = "1"
        self.copyToDirectory = "1";
        self.analysisDirectory  = "1";
        self.sshKey = "1";
        self.userName = "1";
        self.remoteScriptDirectory = "1";
        self.binaryDirectoryPath = "1";
        self.desktopUserName = "1";
        self.desktopIPAddress = "1";
        self.desktopHostname = "1";
        self.initDirectory();
    
    def listdir(self, filepath):
        if(filepath.find("/cygdrive")>=0):
            self.getPathWin(filepath);
        return os.listdir(path)
    
#    def initOslistDir(self):
#        self.originListDir = os.listdir;
#        os.listdir = self.listdir;
        
    def initDirectory(self):
        filename = os.path.join("..", "conf","main.conf")
        file = open(filename)
        lines = file.readlines();
        l = []
        for line in lines:
            if(len(string.strip(line)) == 0):
                continue;
            if line.find("#") != 0:
                tup = string.split(line,maxsplit=1);
                if(tup[0]=="copyToDirectory"):
                    self.copyToDirectory = string.strip(tup[1]);
#                if(tup[0]=="analysisDirectory"):
#                    self.analysisDirectory = string.strip(tup[1]);
                if(tup[0]=="sshKey"):
                    self.sshKey = string.strip(tup[1]);
                if(tup[0]=="userName"):
                    self.userName = string.strip(tup[1]);
                if(tup[0]=="remoteScriptDirectory"):
                    self.remoteScriptDirectory = string.strip(tup[1]);
                if(tup[0] == "binaryDirectoryPath"):
                    self.binaryDirectoryPath = string.strip(tup[1]);
                if(tup[0] == "path"):
                    self.path = string.strip(tup[1]);
                if(tup[0] == "desktopUserName"):
                    self.desktopUserName = string.strip(tup[1]);
                if(tup[0] == "desktopIPAddress"):
                    self.desktopIPAddress = string.strip(tup[1]);
                if(tup[0] == "desktopHostname"):
                    self.desktopHostname = string.strip(tup[1]);
                    
        file.close();
#        print self.copyToDirectory;
#        print self.analysisDirectory;
#        print self.sshKey;
#        print self.userName;
#        print self.remoteScriptDirectory;
    def getPath(self):
        return fm(self.path);
    
    def getPathLinux(self):
        return toLinux(self.path);
    def getPathWin(self):
        return toWinFile(self.path)
    
    def getAnalysisDataPath(self):
        if(sys.platform.find("linu")>=0):
            return self.getPath();
        if(sys.platform.find("win")>=0):
            return fm(self.copyToDirectory);

    """
    the value return by this function is different from the one returned in ConfigBase.getAutoSave()
    """
    def getAutoSavePath(self, expName):
        if(sys.platform.find("linu")>=0):
            p = self.getPath()
            ret = os.path.join(p, expName, "autosave")
            ret = fm(ret);
            return ret
        if(sys.platform.find("win")>=0):
            p = self.copyToDirectory;
            ret = p + "/" + expName + "/autosave";
            ret = toWinFile(ret);
            return ret;
    
    def getSleepTime(self, maxYear, servername, expName= "", factor=""):
        expName = ConfigBase.getNameWithReplayPrefix(expName)
        timelimit = 3600 * maxYear + 300
        hour = string.atoi(time.strftime("%H",time.localtime()))
        weekday = string.atoi(time.strftime("%w",time.localtime()))
        if servername != "fs3.das4.tudelft.nl":
            if weekday == 6 or weekday == 0:
                return timelimit
            if hour >= 8 and hour <20 :
                return 900
        return timelimit
            
    def getTimelimit(self, maxYear, servername, expName= "", factor=""):
        t = self.getSleepTime(maxYear, servername, expName, factor)
        return "-t %d "%t
        
    def getPathExp(self, expName):
        p = self.getPath();
        return fm(os.path.join(p, expName))
    
    def setHostName(self, var):
        self.hostname = var
    
    def set1a13AI(self,num):
#        if num !=0:
#            self.set("difficulty", "max_no_competitors", 5)
#        else:
#            self.set("difficulty", "max_no_competitors", 4)
        game_start_scr_path = self.getGameStartScrPath()
        file = open(game_start_scr_path, "w")
        if num!=0:
            print >> file, "start_ai " + moreAICommands[num-1]
        for i in range(0, 4):
            print >>file, "start_ai " + "simpleAI"
        file.close()
    
    def set1a14AI(self,num):
#        self.set("difficulty", "max_no_competitors", 1)
        game_start_scr_path = self.getGameStartScrPath()
        file = open(game_start_scr_path, "w")
        if num!=0:
            print >> file, "start_ai " + moreAICommands[num-1]
        file.close()
        
    def set1a15AI(self,num):
#        self.set("difficulty", "max_no_competitors", 2)
        game_start_scr_path = self.getGameStartScrPath()
        file = open(game_start_scr_path, "w")
        if num!=0:
            print >> file, "start_ai " + moreAICommands[num-1]
            print >> file, "start_ai Rondje"
        file.close()

    def expVarChange(self, expName, var):
        expName = ConfigBase.getNameWithReplayPrefix(expName)
        if (expName[0:1] == "1"):
            self.setRandomAI(16)
        if expName.find("1a14-") >=0:
            self.set1a14AI(var)
        if expName.find("1a15-") >=0:
            self.set1a15AI(var)
        if(expName == "1a1"):
#            self.set("difficulty", "max_no_competitors", var)
            self.setAI(var)
        if(expName == "1a13" or expName == "1a13-5" or expName == "1a13-6"):
            self.set1a13AI(var)
        if(expName == "1a5"):
#            self.set("difficulty", "max_no_competitors", 1)
            self.setSingleAI(var)
        if(expName == "1a6-64"):
#            self.set("difficulty", "max_no_competitors", var)
            self.setRandomAI(var)
            self.set("game_creation", "map_x", 6)
            self.set("game_creation", "map_y", 6)
        if(expName == "1a6-128"):
#            self.set("difficulty", "max_no_competitors", var)
            self.setRandomAI(var)
            self.set("game_creation", "map_x", 7)
            self.set("game_creation", "map_y", 7)
        if(expName == "1a6-256"):
#            self.set("difficulty", "max_no_competitors", var)
            self.setRandomAI(var)
            self.set("game_creation", "map_x", 8)
            self.set("game_creation", "map_y", 8)
    
        if(expName == "1a6-1024"):
#            self.set("difficulty", "max_no_competitors", var)
            self.setRandomAI(var)
            self.set("game_creation", "map_x", 10)
            self.set("game_creation", "map_y", 10)
        if(expName == "1a6-2048"):
#            self.set("difficulty", "max_no_competitors", var)
            self.setRandomAI(var)
            self.set("game_creation", "map_x", 11)
            self.set("game_creation", "map_y", 11)
        if expName == "1a2":
            self.set("game_creation", "map_x", var)
            self.set("game_creation", "map_y", var)
#            --------------
#            self.set("difficulty", "max_no_competitors", 16)
            self.setRandomAI(16)
            self.set("network", "MAX_COMPANIES", 16)#stupid config ini file
        if expName == "1a3":
            self.set("difficulty", "number_towns", var)
            self.set("difficulty", "number_industries", var)
        if expName == "1a4":
#            self.set("difficulty", "max_no_competitors", 16)
            self.setRandomAI(16)
            self.set("game_creation", "map_x", 11)
            self.set("game_creation", "map_y", 11)
        if(expName == "1a6"):
#            self.set("difficulty", "max_no_competitors", var)
            self.setRandomAI(var)
        if(expName.find("1a7")>=0):
#            self.set("difficulty", "max_no_competitors", var)
            self.setRandomAI(var)
            self.set("network", "MAX_COMPANIES", var)#stupid openttd, config ini file
        if(expName.find("2a")>=0) or expName.find("3a")>=0:
#            self.set("difficulty", "max_no_competitors", var)
            self.set("network", "MAX_COMPANIES", var)#stupid openttd, config ini file
            self.set("network", "max_clients", var)
#            print "set network, MAX_COMPANIES %d"%var
            self.setAI(0)
        if(expName.find("-op") >=0):
            op = string.atoi(expName[expName.find("-op") + 3:]);
            self.set("ai", "ai_max_opcode_till_suspend", op)
            print "max opcode till suspend", op
        if(expName.find("-2048")>=0):
            self.set("game_creation", "map_x", 11)
            self.set("game_creation", "map_y", 11)
        if(expName.find("-1024")>=0):
            self.set("game_creation", "map_x", 11)
            self.set("game_creation", "map_y", 11)
        DescriptionParser.config(expName, var) 
    def getHostName(self):
        if self.hostname == "1":
            file = os.popen("hostname")
            lines = file.readlines()
            self.hostname = string.strip(lines[0])
        return self.hostname
    
    def isInDAS(self):
        hostname = self.getHostName();
        if(hostname.find("fs") >=0):
            return True;
        return False;
    
    def appendAddress(self,address):
        if address.find("nl")>=0:
            return address
        if address[4:5] == "0":
            address = address + ".das4.cs.vu.nl"
        elif address[4:5] == "1":
            address = address + ".das4.liacs.nl"
        elif address[4:5] == "2":
            address = address + ".das4.science.uva.nl"
        elif address[4:5] == "4":
            address = address + ".das4.science.uva.nl"
        elif address[4:5] == "3":
            address = address + ".das4.tudelft.nl"
        return address

    def getServerAddress(self):
        f = open("/home/sshen/serveraddress.txt")
        address = f.readlines()[0] 
        address = string.strip(address)
        address = self.appendAddress(address)
        f.close()
        return address

    def getCPUMEMFileName(self, expId,expName, factor):
        path = self.getPath()
        print "getCPUMEMFileName", path
        hostname = self.getHostName()
        p2 = os.path.join(path, "%d_"%expId+expName+"_%d_"%factor+"cpumem"+hostname)
        print "getCPUMEMFileName", p2
        return fm(p2)
    
    def getPortFileName(self, expId, expName, factor):
        path = self.getPath()
        hostname = self.getHostName()
        p2 = os.path.join(path, "%d_"%expId+expName+"_%d_"%factor + "port" +hostname)
        return fm(p2)
    
    def getPackageName(self, expId, expName, factor):
        path = self.getPath()
        hostname = self.getHostName()
        p2 = os.path.join(path, "%d_"%expId+expName+"_%d_"%factor + "package" +hostname)
        return fm(p2)
    
    def getPackageResult(self, expId, expName, factor):
        path = self.getPath()
        hostname = self.getHostName()
        p2 = os.path.join(path, "%d_"%expId+expName+"_%d_"%factor + "packageResult" +hostname)
        return fm(p2)
    
    def getExpLog(self, expId, expName, factor):
        path = self.getPathExp(expName)
        hostname = self.getHostName()
        filename = "%d"%expId+ "_" + expName + "_"+"%d_"%factor + hostname +"_log.txt"
        return fm(os.path.join(path,filename))
    
    def getNetworkResultFile(self, expId, expName, factor):
        hostname = self.getHostName()
        dir = self.getPathExp(expName)
        childDir = os.path.join(dir, "network")
        filename = "%d_"%expId + expName + "_%d_"%factor + hostname + "network.txt"
        return fm(os.path.join(childDir, filename))
    
    def getFinalCpuMemFileName(self, expId, expName, factor):
        path = self.getPathExp(expName)
        hostname = self.getHostName()
        newfilename = "%d"%expId + "_" + expName + "_%d"%factor+"_cpu_"+ hostname + ".txt"
        return fm(os.path.join(path, "analysis", newfilename))
    
    def isFinalResultFile(self, expId, expName, filename):
        if expId !=0:
            if filename.find("%d_"%expId + expName) >=0:
                if filename.find("_cpu_") >=0:
                    return True
            return False
        if filename.find(expName) >=0:
            if filename.find("_cpu_") >=0:
                return True
        return False
    def getCpuMemFileNameTemplate(self, expId,expName, factor, isNetwork=False):
        if isNetwork == False:
            if expId != 0:
                return "%d"%expId + "_" + expName + "_%d"%factor+"_cpu_";
            return "_" + expName + "_%d"%factor+"_cpu_";    
        else:
            if expId != 0:
                return "%d"%expId + "_" + expName + "_%d"%factor;
            return "_" + expName + "_%d_"%factor;    
    #def saveNetworkFile():
    #    id = getId()
    #    packetFileName = os.path.join('..', "test_result", "packet")
    #    if os.path.exists(os.path.join("..", "test_result", "trunk", "%d_"%id + "packet")) == False:
    #        shutil.copy(packetFileName, os.path.join("..", "test_result", "trunk", "%d_"%id + "packet"))
    
    def saveCPUandNetworkFile(self):
        return
    #ver= ""
    #ver = "%s"%sys.version
    #print ver
    '''
    number_of_industry = 3 normal
                       = 4 high
    '''

if __name__=="__main__":
#    config = ConfigParser.ConfigParser()
#    config.readfp(open('C:\Users\Q\Documents\OpenTTD\openTTD.cfg'))
#    ttdVersion = config.get("difficulty", "competitor_speed")
#    print getId()
#    increaseId()
    c = Configuration();
#    c.expVarChange("1a7-1024-op40000", 0)
#    c.initExp("1a12")
#    c.expVarChange("1a12", 1)
#    print c.getMaxYear("1a14-5y")
#    c.set("network", r"MAX_COMPANIES", 100)
#    pass
'''
Invoke the openttd.exe ,and then use pslist to find the pid of the process,
it will be used to kill the process after 2 hours
'''
#playGameCmd = "C:\Program Files\OpenTTD\openttd.exe -g"
#os.system("")